import json, os, re
from core.base_tornado_request_handler import BaseTornadoRequestHandler
from db import LogsDB

class ApiCraftHandler(BaseTornadoRequestHandler):
  async def get(self, action):
    if action == "get_log":
      get_all_lines = self.get_query_argument("all", default="0")
      data = []
      log_dir = os.getenv("LOG_DIR")
      log_file = os.path.join(log_dir, "WonewTigerHelper.lua")
      with open(log_file, "r", encoding='utf-8') as file:
        for line in file:
          line_data = self.parse_log_line(line)
          if line_data:
            data.append(self.parse_log_line(line))
      if get_all_lines == "1":
        self.return_json(data)
      else:
        self.return_json(data[-10000:])

  async def post(self, action):
    if action == "clear_log_file":
      log_dir = os.getenv("LOG_DIR")
      log_file = os.path.join(log_dir, "WonewTigerHelper.lua")
      log_backup_file = os.path.join(log_dir, "WonewTigerHelper.lua.bak")
      if os.path.exists(log_file):
        os.remove(log_file)
      if os.path.exists(log_backup_file):
        os.remove(log_backup_file)
      self.return_json({"success": log_dir})

  async def get_list(self):
    log_list = await LogsDB.all()
    self.return_json({"list": [log.to_dict() for log in log_list]})
  
  async def clear_role(self):
    num = await LogsDB.all().delete()
    self.return_json({"num": num})
  
  def parse_log_line(self, log_str):
      pattern = r"\[(.*?)\](.*?)\{(.*?)\}"
      match = re.search(pattern, log_str)
      if not match:
        return None
      return log_str
      # if not "CHECK_REAGENTS" in log_str and not "TRADE_SKILL_ITEM_CRAFTED_RESULT" in log_str:
      #   return None
      # pattern = r"\[(.*?)\](.*?)\{(.*?)\}"
      # match = re.search(pattern, log_str)
      # if not match:
      #   return None
      # item_dict = {}
      # item_dict["time"] = match.group(1)
      # item_dict["type"] = "CHECK_REAGENTS" if "CHECK_REAGENTS" in log_str else "TRADE_SKILL_ITEM_CRAFTED_RESULT"
      # regents_list = []
      # resourcesReturned_list = []
      # for item in match.group(3).split("&"):
      #     item_id, item_value = item.split("=")
      #     if "itemID_" in item_id:
      #         regents_list.append({"itemId": int(item_id.replace("itemID_", "")), "count": int(item_value)})
      #     if "resourcesReturned_" in item_id:
      #         resourcesReturned_list.append({"itemId": int(item_id.replace("resourcesReturned_", "")), "count": int(item_value)})
      #     item_dict[item_id] = item_value
      # item_dict["regents_list"] = regents_list
      # item_dict["resourcesReturned_list"] = resourcesReturned_list
      # return item_dict